package cn.akwangl.controller;

import cn.akwangl.interceptor.LoggerWrapper;
import cn.akwangl.interceptor.SystemInterceptor;
import cn.akwangl.pojo.User;
import cn.akwangl.pojo.UserQuery;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户中心
 *
 * @author youyongkun
 * @date 2022/5/16 19:28
 * @since 0.0.2
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerWrapper.getLogger(UserController.class);

    private List<User> dataList;

    @PostConstruct
    public void dataInit() {
        List<User> list = new ArrayList();
        User user1 = new User(1L, "菠萝吹雪", "123456", "wetqs1", LocalDate.of(2022, 04, 01));
        User user2 = new User(2L, "橙留香", "123456", "w34we1", LocalDate.of(1996, 07, 24));
        User user3 = new User(3L, "路小路", "123456", "92sfw1", LocalDate.of(1893, 05, 11));

        list.add(user1);
        list.add(user2);
        list.add(user3);

        dataList = list;
    }

    @GetMapping("/getUser")
    public Object getUserBirthday(@RequestParam("id") String id) {
        log.info("当前操作用户:{}", SystemInterceptor.getGlobalUser().getName());
        Optional<User> firstUser = dataList.stream()
                .filter(user -> String.valueOf(user.getId()).equals(id))
                .findFirst();
        return getResultMap(200, "操作成功", firstUser.isPresent() ? firstUser.get() : null);
    }

    @PostMapping("/list")
    public Object list(@RequestBody UserQuery userQuery) {
        log.info("当前操作用户:{}", SystemInterceptor.getGlobalUser().getName());
        List<User> list = dataList.stream()
                .filter(user -> user.getName().equals(userQuery.getUserName()))
                .collect(Collectors.toList());
        return getResultMap(200, "操作成功", list);
    }

    @PostMapping("/error")
    public Object error(@RequestBody UserQuery userQuery) {
        log.info("当前操作用户:{}", SystemInterceptor.getGlobalUser().getName());
        int x = 1 / 0;
        return getResultMap(200, "操作成功", dataList);
    }

    private Map<String, Object> getResultMap(int code, String msg, Object data) {
        Map<String, Object> result = new HashMap(3);
        result.put("code", code);
        result.put("msg", msg);
        result.put("data", data);
        return result;
    }
}
